<template>
  <div class="config-container">
    <!-- 顶部操作栏 -->
    <header class="header">
      <div class="title">闭环节点配置</div>
      <div class="button-group">
        <el-button @click="handleCloneNode" type="primary" icon="DocumentCopy">克隆节点</el-button>
        <el-button @click="handleAddNode" type="success" icon="Plus">新增节点</el-button>
        <el-button @click="handleSaveCheck" type="warning" icon="Save">检测保存</el-button>
      </div>
    </header>

    <!-- 节点列表 -->
    <div class="node-list">
      <div
        v-for="(node, index) in nodeList"
        :key="node.NODE_ID"
        class="node-item"
        :class="{ 'dragging': isDragging }"
      >
        <div class="content">
          <div class="node-name">{{ node.NODE_NAME }}</div>
          <div class="order">执行顺序：{{ node.LOOP_NODE_ORDER_NUM }}</div>
          <div class="actions">
            <!-- 上移按钮 -->
            <el-tooltip content="上移节点" placement="top">
              <el-button 
                v-if="index > 0"
                @click="moveNode(index, 'up')"
                
                circle
                plain
              />
            </el-tooltip>

            <!-- 下移按钮 -->
            <el-tooltip content="下移节点" placement="top">
              <el-button 
                v-if="index < nodeList.length - 1"
                @click="moveNode(index, 'down')"
                
                circle
                plain
              />
            </el-tooltip>

            <!-- 删除按钮 -->
            <el-tooltip content="删除节点" placement="top">
              <el-button 
                @click="handleDeleteNode(index)"
                
                circle
                type="danger"
                plain
              >
          <!-- 添加删除图标 -->
            <el-icon><Delete /></el-icon>
              </el-button>              
            </el-tooltip>

            <!-- 检查规则按钮 -->
           <!-- 检查规则按钮 -->
            <el-button
              @click="handleCheckRule(node)"
              type="primary"
              plain
              size="small"
            >
              检查规则
            </el-button>

            <!-- 查看信息按钮 -->
            <el-button
              @click="handleViewInfo(node)"
              type="info"
              plain
              size="small"
            >
              查看信息
            </el-button>
            <!-- 新增：侧边栏抽屉 -->
          </div>
        </div>
      </div>
    </div>
    <el-drawer
      v-model="isInfoDrawerVisible"
      :title="currentNode.NODE_NAME + ' 详细信息'"
      direction="ltr"
      size="50%"
      :before-close="handleCloseDrawer"
      :modal="true"
      :append-to-body="true"
    >
    <CloseConfigC_a 
    :node-id="currentNode.NODE_ID" 
    :node-name="currentNode.NODE_NAME" 
    :node-num="Number(currentNode.LOOP_NODE_ORDER_NUM)" 
     @close="isInfoDrawerVisible = false" 
    />
    </el-drawer>

    <!-- 操作反馈 -->
    <el-alert
      v-if="statusMessage"
      :title="statusMessage"
      :type="statusType"
      closable
      @close="clearStatus"
      class="status-alert"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { closeLoopDetail } from '@/stores/closeLoopList.js';
import { useRoute } from 'vue-router';
import CloseConfigC_a  from '@/pages/home/close/CloseConfigC_a.vue'; // 引入组件

const route = useRoute();
const closeLoopId = route.query.closeLoopId;//获取闭环ID
// 引入Store
const store = closeLoopDetail();

// 状态管理
const nodeList = computed(() => store.closeLoopDeatilList);
const isDragging = ref(false);
const statusMessage = ref('');
const statusType = ref('success');
// 新增：控制抽屉状态和当前节点
const isInfoDrawerVisible = ref(false);
const currentNode = ref({});

// 查看信息按钮的点击事件
const handleViewInfo = (node) => {
  currentNode.value = node;
  isInfoDrawerVisible.value = true;
};

// 关闭抽屉的回调
const handleCloseDrawer = () => {
  isInfoDrawerVisible.value = false;
};

// 初始化数据
onMounted(async () => {
  try {
    await store.getCloseLoopDeatilList(closeLoopId);
    statusMessage.value = '数据加载成功';
  } catch (error) {
    statusMessage.value = `加载失败: ${error.message}`;
    statusType.value = 'error';
  }
});

// 操作函数
const handleCloneNode = () => {
  if (nodeList.value.length === 0) {
    ElMessage.warning('请先添加或选择节点');
    return;
  }
  const cloneNode = structuredClone(nodeList.value[0]);
  cloneNode.NODE_ID = generateUUID();
  cloneNode.LOOP_NODE_ORDER_NUM = nodeList.value.length + 1;
  store.closeLoopDeatilList.push(cloneNode);
  updateNodeOrder();
  statusMessage.value = '节点克隆成功';
};

const handleAddNode = () => {
  const newNode = {
    NODE_ID: generateUUID(),
    NODE_NAME: '新节点',
    LOOP_NODE_ORDER_NUM: nodeList.value.length + 1,
    // 其他默认字段...
  };
  store.closeLoopDeatilList.push(newNode);
  statusMessage.value = '新增节点成功';
};

const handleSaveCheck = async () => {
  try {
    // 调用后端API验证并保存
    //await saveToServer(nodeList.value);
    statusMessage.value = '保存成功';
  } catch (error) {
    statusMessage.value = `保存失败: ${error.message}`;
    statusType.value = 'error';
  }
};

const moveNode = (index, direction) => {
  const targetIndex = direction === 'up' ? index - 1 : index + 1;
  if (targetIndex < 0 || targetIndex >= nodeList.value.length) return;

  const temp = nodeList.value[index];
  store.closeLoopDeatilList.splice(index, 1);
  store.closeLoopDeatilList.splice(targetIndex, 0, temp);
  updateNodeOrder();
  statusMessage.value = `节点移动成功`;
};

const handleDeleteNode = (index) => {
  ElMessage.confirm(
    '确定删除该节点？此操作不可逆！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    store.closeLoopDeatilList.splice(index, 1);
    updateNodeOrder();
    statusMessage.value = '节点删除成功';
  });
};

// 辅助函数
const generateUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    const r = (Math.random() * 16) | 0,
      v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

const updateNodeOrder = () => {
  store.closeLoopDeatilList.forEach((node, idx) => {
    node.LOOP_NODE_ORDER_NUM = idx + 1;
  });
};

const clearStatus = () => {
  statusMessage.value = '';
  statusType.value = 'success';
};

// 模拟API调用（需替换为真实接口）


// 交互增强（如拖拽排序）
// const startDrag = () => {
//   isDragging.value = true;
// };
// const endDrag = () => {
//   isDragging.value = false;
//   updateNodeOrder();
// };
// 拖拽排序逻辑（可选）
// const handleDragStart = (event, node) => {
//   event.dataTransfer.setData('text/plain', node.NODE_ID);
// };
// const handleDragOver = (event) => {
//   event.preventDefault();
// };
// const handleDrop = (event, targetNode) => {
//   const draggedNodeId = event.dataTransfer.getData('text/plain');
//   // 实现拖拽排序逻辑
// };
</script>

<style scoped>
/* 抽屉样式调整 */
.el-drawer__container {
  overflow: auto;
}

.el-drawer.ltr {
  left: 0 !important; /* 确保左侧弹出 */
  right: auto !important;
}
.config-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 1.2em;
  font-weight: bold;
}

.button-group {
  display: flex;
  gap: 10px;
}

.node-list {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.node-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
  transition: background-color 0.3s;
}

.node-item:hover {
  background-color: #f5f7fa;
}

.content {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 20px;
}

.node-name {
  flex: 1;
  font-weight: bold;
}

.order {
  margin-right: 20px;
}

.actions {
  display: flex;
  gap: 8px;
}

.status-alert {
  margin-top: 20px;
  width: 100%;
}

/* 拖拽样式（可选） */
.dragging {
  opacity: 0.7;
  cursor: grabbing;
}
</style>